const sequelize = require("../sequelize_ins");
const { DataTypes } = require("sequelize");
const { TIME_TYPE_DESC } = require("../../sys_config");

const core = sequelize.define("applys", {
  department_id: DataTypes.INTEGER,
  disease_id: DataTypes.INTEGER,
  d_id: DataTypes.INTEGER,
  name: DataTypes.STRING,
  sex: DataTypes.INTEGER,
  age: DataTypes.INTEGER,
  phone: DataTypes.STRING,
  date: DataTypes.DATEONLY,
  time_type: DataTypes.INTEGER,
  date_time: {
    type: DataTypes.VIRTUAL,
    get() {
      return (
        this.getDataValue("date") +
        " " +
        TIME_TYPE_DESC[this.getDataValue("time_type")]
      );
    },
    set(val) {
      const [d, t] = val.split(" ");
      this.setDataValue("date", d);
      for (let type in TIME_TYPE_DESC)
        if (type === t) {
          this.setDataValue("time_type", TIME_TYPE_DESC[type]);
          break;
        }
    },
  },
  desc: DataTypes.TEXT,
  status: DataTypes.INTEGER,
});

module.exports = {
  core,

  async get_applys(query) {
    const data = await this.core.findAll({
      where: query,
      include: ["doctor", "department", "disease"],
    });
    return data.map((raw) => ({
      id: raw.id,
      u_id: raw.u_id,
      d_id: raw.d_id,
      name: raw.name,
      phone: raw.phone,
      sex: raw.sex,
      age: raw.age,
      doctor: raw.doctor.name,
      department_disease: `${raw.department.name}/${raw.disease.name}`,
      department: raw.department.name,
      disease: raw.disease.name,
      desc: raw.desc,
      date: raw.date,
      time_type: raw.time_type,
      date_time: `${raw.date} ${TIME_TYPE_DESC[raw.time_type]}`,
      status: raw.status,
    }));
  },
};
